package cn.youyeku.sockettransmission.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.obsez.android.lib.filechooser.ChooserDialog;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import cn.youyeku.sockettransmission.CLIENT.ConstantClient;
import cn.youyeku.sockettransmission.CLIENT.FileClient;
import cn.youyeku.sockettransmission.CLIENT.TextClient;
import cn.youyeku.sockettransmission.R;
import cn.youyeku.sockettransmission.adapter.ChatAdapter;
import cn.youyeku.sockettransmission.bean.MessageType;
import cn.youyeku.sockettransmission.bean.Msg;
import cn.youyeku.sockettransmission.ui.ConstantAppConfig;
import cn.youyeku.sockettransmission.utils.LogUtils;

import static cn.youyeku.sockettransmission.bean.MessageType.MESSAGE_SEND_FILE;
import static cn.youyeku.sockettransmission.ui.ConstantAppConfig.IP;
import static cn.youyeku.sockettransmission.ui.ConstantAppConfig.PORT;

public class ChatFragment extends BaseFragment implements View.OnClickListener {

    TextClient socketClientChat;
    FileClient socketClientFile;
    private RecyclerView mRecycleView;
    private ChatAdapter mMsgAdapter;
    List<Msg> mMsgList = new ArrayList<>();

    LocalBroadcastManager lbm;
    /**
     * 请输入要发送的内容
     */
    private EditText mEtInput;
    /**
     * 发送
     */
    private Button mBtSend;
    String path;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MessageType.MESSAGE_TYPE_FRIEND:
                    mMsgAdapter.notifyDataSetChanged();
                    break;
                case MessageType.MESSAGE_TYPE_ME:
                    mMsgAdapter.notifyDataSetChanged();
                    break;
                case MESSAGE_SEND_FILE:
                    try {
                        socketClientFile.sendFile(path);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    break;
            }
            scroolToBottom();
        }
    };
    /**
     * 发送文件
     */
    private Button mBtSendFile;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fgm_file, null);
        mRecycleView = (RecyclerView) view.findViewById(R.id.recycle);
        initView(view);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycleView.setLayoutManager(layoutManager);


        mMsgAdapter = new ChatAdapter(mMsgList);
        mRecycleView.setAdapter(mMsgAdapter);


        //注册本地广播
        lbm = LocalBroadcastManager.getInstance(getContext());
        IntentFilter filter = new IntentFilter();
        filter.addAction("youyeku.initClient");

        lbm.registerReceiver(mMessageReceiver, filter);


        return view;
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("youyeku.initClient")) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        initText();
                    }
                }).start();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        initFile();
                    }
                }).start();

                ConstantAppConfig.isStart = true;
            }
        }
    };

    //滑动到底部
    public void scroolToBottom() {
        mRecycleView.scrollToPosition(mMsgList.size() - 1);
    }

    private void initView(View view) {
        mEtInput = (EditText) view.findViewById(R.id.et_input);
        mEtInput.setOnClickListener(this);
        mBtSend = (Button) view.findViewById(R.id.bt_send);
        mBtSend.setOnClickListener(this);
        mBtSendFile = (Button) view.findViewById(R.id.bt_send_file);
        mBtSendFile.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.et_input:
                break;
            case R.id.bt_send:
                if (ConstantAppConfig.isStart) {
                    try {
                        String msg = mEtInput.getText().toString();
                        socketClientChat.sendText(msg);
                        Message message = new Message();
                        mMsgList.add(new Msg(msg, MessageType.MESSAGE_TYPE_ME, ""));
                        message.what = MessageType.MESSAGE_TYPE_ME;
                        handler.sendMessage(message);

                        mEtInput.setText("");

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.bt_send_file:

                new ChooserDialog().with(getActivity())
                        .withStartFile(ConstantAppConfig.PATH)
                        .withChosenListener(new ChooserDialog.Result() {
                            @Override
                            public void onChoosePath(final String filePath, File pathFile) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            LogUtils.w("文件路径" + filePath);
                                            socketClientFile.sendFile(filePath);
                                            Log.w("", "线程结束");
                                        } catch (IOException | InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();

                            }
                        })
                        .build()
                        .show();

                break;
        }
    }

    private void initText() {

        socketClientChat = new TextClient(IP, PORT, ConstantClient.SOCKET_TYPE_TEXT);

        socketClientChat.setTextClientListener(new TextClient.TextClientListener() {
            @Override
            public void onRecMessage(String msg) {
                mMsgList.add(new Msg(msg, MessageType.MESSAGE_TYPE_FRIEND, ""));
                Message message = new Message();
                message.what = MessageType.MESSAGE_TYPE_FRIEND;
                handler.sendMessage(message);
            }
        });
        socketClientChat.init();
    }

    private void initFile() {
        socketClientFile = new FileClient(IP, PORT, ConstantClient.SOCKET_TYPE_FILE);
        socketClientFile.setFileClientListener(new FileClient.FileClientListener() {
            @Override
            public void onRecFile() {

            }

            @Override
            public void onRecSuccess(String fileName) {

                FramentThreadShortToast(getActivity(), "接收文件" + fileName);

            }
        });
        socketClientFile.init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        lbm.unregisterReceiver(mMessageReceiver);
    }
}
